// pages/book-detail/book-detail.js
import {BookModel} from "../../models/book.js";
import {LikeModel} from "../../models/like.js";

const utils = require("../../utils/util.js");
const bookModel = new BookModel()
const likeModel = new LikeModel()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        comments: [],
        book: null,
        likeStatus: false,
        likeCount: 0,
        posting: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        utils.showNavigationBarLoading()
        const bid = options.bid
        const detail = bookModel.getDetail(bid)
        const comments = bookModel.getComment(bid)
        const likeStatus = bookModel.getLikeStatus(bid)

        Promise.all([detail,comments,likeStatus])
            .then((res)=>{
                utils.hideNavigationBarLoading(res[0].title)
                this.setData({
                    book:res[0],
                    comments:res[1].comments,
                    likeCount: res[2].fav_nums,
                    likeStatus: res[2].like_status
                })
            })
    },

    onlive(e) { // 点赞
        const like_or_cancel = e.detail.state
        likeModel.live(like_or_cancel, this.data.book.id, 400)
    },

    onFakePost() { // 打开评论
        this.setData({
            posting: true
        })
    },

    onCancel() { // 关闭评论
        this.setData({
            posting: false
        })
    },

    onPost(e) { // 评论
        const commont = e.detail.content || e.detail.value

        if (!commont) {
            return
        }

        if (commont.length > 12) {
            wx.showToast({
                title: "评论不能多于12个字",
                icon: "none"
            })
            return
        }

        bookModel.addComment(this.data.book.id, commont)
            .then((res) => {
                wx.showToast({
                    title: '+1',
                    icon: 'none'
                })


                this.data.comments.unshift({
                    content:commont,
                    nums: 1
                })

                this.setData({
                    comments: this.data.comments,
                    posting: false
                })
            })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})